<?php
/**
 * Created by littleU.
 * User: littleU
 * Date: 2021-02-01
 * Time: 16:46
 */

namespace app\api\service;

use app\common\tool\IAuth;
use app\api\model\Admin as AdminModel;
use app\lib\exception\TokenException;


class CmsToken extends Token
{
    public function get($mobile, $password)
    {
        $admin = AdminModel::check($mobile, IAuth::setPassword($password));
        if(!$admin)
        {
            throw new TokenException([
                'msg'  => '授权失败',
                'errorCode' => 10004
            ]);
        }
        else
        {
            $admin->last_login_time = time();
            $admin->last_login_ip = request()->ip();
            $admin->save();
            $scope = $admin->scope;
            $uid = $admin->id;
            $values = [
                'scope' => $scope,
                'uid' => $uid
            ];
            $token = $this->saveToCache($values);
            return $token;
        }
    }

    private function saveToCache($values)
    {
        $token = self::generateToken();
        $result = cache($token, json_encode($values));
        if(!$result)
        {
            throw new TokenException([
                'msg'  => '服务器缓存失败',
                'errorCode' => 10005
            ]);
        }
        return $token;
    }
}